<script setup lang="ts">
import { ref, onMounted } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { VideoPlay, Plus, Download, CopyDocument, Link } from "@element-plus/icons-vue"
import ImagePreview from "@/components/ImagePreview.vue"
import { getGoodPageApi, getGoodCategoriesApi, updateGoodEnableApi, type GoodInfo, type GoodsCategoryRecord, type GoodUpdateEnableReq } from "@/api/good"
import GoodForm from "./components/GoodForm.vue"

// 查询参数类型
interface SearchType {
  id: string
  category: string
  enable: boolean | null
}

// 查询参数
const searchParams = ref<SearchType>({
  id: "",
  category: "",
  enable: null
})

// 物品分类选项
const categoryOptions = ref<GoodsCategoryRecord[]>([])

// 图片预览相关
const previewVisible = ref(false)
const previewImageUrl = ref("")
const previewTitle = ref("")

// 动效预览相关
const animationPreviewVisible = ref(false)
const animationPreviewUrl = ref("")
const animationPreviewTitle = ref("")

// 物品表单相关
const goodFormVisible = ref(false)
const currentGoodData = ref<GoodInfo | null>(null)
const isEditMode = ref(false)

// 数据列表和分页
const dataList = ref<GoodInfo[]>([])
const loading = ref(false)
const totals = ref(0)
const pageInfo = ref({
  page: 1,
  pageSize: 10
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchParams.value,
      pageNum: pageInfo.value.page,
      pageSize: pageInfo.value.pageSize
    }
    
    // 过滤空值参数
    const requestParams = Object.fromEntries(
      Object.entries(params).filter(([_, value]) => {
        return value !== '' && value !== null && value !== undefined
      })
    )
    
    const response = await getGoodPageApi(requestParams)
    const { data } = response
    dataList.value = data.list
    totals.value = data.total
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载物品分类
const loadCategories = async () => {
  try {
    const response = await getGoodCategoriesApi()
    categoryOptions.value = response.data
  } catch (error) {
    console.error('加载物品分类失败:', error)
  }
}

// 查询方法
const handleSearch = () => {
  pageInfo.value.page = 1
  loadData()
}

// 重置方法
const handleReset = () => {
  searchParams.value = {
    id: "",
    category: "",
    enable: null
  }
  pageInfo.value.page = 1
  loadData()
}

// 新增物品
const handleAdd = () => {
  isEditMode.value = false
  currentGoodData.value = null
  goodFormVisible.value = true
}

// 编辑物品
const handleEdit = (row: GoodInfo) => {
  isEditMode.value = true
  currentGoodData.value = { ...row }
  goodFormVisible.value = true
}

// 切换上架状态
const handleToggleStatus = async (row: GoodInfo) => {
  const newEnable = !row.enable
  const actionText = newEnable ? '上架' : '下架'
  const itemName = row.name.zh || row.name.en || row.name.ar || row.id
  
  try {
    await ElMessageBox.confirm(
      `确定要${actionText}物品"${itemName}"吗？`,
      `${actionText}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true
      }
    )
    
    const params: GoodUpdateEnableReq = {
      enable: newEnable
    }
    
    await updateGoodEnableApi(row.id, params)
    
    // 更新本地数据
    row.enable = newEnable
    
    ElMessage.success(`${actionText}成功`)
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作，不做任何处理
      return
    }
    console.error('切换状态失败:', error)
    ElMessage.error(`${actionText}失败`)
  }
}

// 分页方法
const handleSizeChange = (size: number) => {
  pageInfo.value.pageSize = size
  pageInfo.value.page = 1
  loadData()
}

const handleCurrentChange = (page: number) => {
  pageInfo.value.page = page
  loadData()
}

// 图片预览
const handlePreviewImage = (url: string, title: string) => {
  previewImageUrl.value = url
  previewTitle.value = title
  previewVisible.value = true
}

// 动效预览
const handlePreviewAnimation = (url: string, title: string) => {
  animationPreviewUrl.value = url
  animationPreviewTitle.value = title
  animationPreviewVisible.value = true
}

// 获取文件扩展名
const getFileExtension = (url: string) => {
  const extension = url.split('.').pop()?.toUpperCase()
  return extension || '未知格式'
}

// 获取动效文件类型
const getAnimationFileType = (url: string) => {
  // 先移除查询参数，再获取扩展名
  const urlWithoutQuery = url.split('?')[0]
  const extension = urlWithoutQuery.split('.').pop()?.toLowerCase()
  if (!extension) return '未知格式'
  
  const supportedTypes = ['webp', 'svga', 'mp4', 'png']
  if (supportedTypes.includes(extension)) {
    return extension.toUpperCase()
  }
  
  return '其他格式'
}

// 获取动效文件类型标签样式
const getAnimationFileTypeTag = (url: string) => {
  // 先移除查询参数，再获取扩展名
  const urlWithoutQuery = url.split('?')[0]
  const extension = urlWithoutQuery.split('.').pop()?.toLowerCase()
  if (!extension) return 'info'
  
  switch (extension) {
    case 'webp':
      return 'success'
    case 'svga':
      return 'warning'
    case 'mp4':
      return 'danger'
    case 'png':
      return 'primary'
    default:
      return 'info'
  }
}

// 下载动效文件
const downloadAnimation = () => {
  const link = document.createElement('a')
  link.href = animationPreviewUrl.value
  link.download = `animation.${getFileExtension(animationPreviewUrl.value).toLowerCase()}`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('开始下载动效文件')
}

// 复制动效链接
const copyAnimationUrl = async () => {
  try {
    await navigator.clipboard.writeText(animationPreviewUrl.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 新窗口打开动效
const openAnimationInNewTab = () => {
  window.open(animationPreviewUrl.value, '_blank')
}

// 获取分类名称
const getCategoryName = (category: string) => {
  const found = categoryOptions.value.find(item => item.key === category)
  return found ? found.desc : category
}

// 获取分类标签样式
const getCategoryTagType = (category: string) => {
  const found = categoryOptions.value.find(item => item.key === category)
  if (!found) return 'info'
  
  // 根据分类的code值来分配不同的标签样式
  const tagTypes = ['', 'primary', 'success', 'warning', 'danger', 'info']
  const typeIndex = found.code % tagTypes.length
  return tagTypes[typeIndex] || 'info'
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 处理表单提交
const handleFormSubmit = () => {
  loadData() // 重新加载数据
}

// 组件挂载时加载数据
onMounted(() => {
  loadCategories()
  loadData()
})
</script>

<template>
  <div class="good-list">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="物品ID">
          <el-input 
            v-model="searchParams.id" 
            placeholder="请输入物品ID" 
            clearable 
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="物品类型">
          <el-select 
            v-model="searchParams.category" 
            placeholder="请选择物品类型" 
            clearable 
            style="width: 200px;"
          >
            <el-option label="全部" value="" />
            <el-option 
              v-for="category in categoryOptions" 
              :key="category.key" 
              :label="category.desc" 
              :value="category.key" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select 
            v-model="searchParams.enable" 
            placeholder="请选择上架状态" 
            clearable 
            style="width: 200px;"
          >
            <el-option label="已上架" :value="true" />
            <el-option label="未上架" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd" style="margin-left: 10px;">
            <el-icon><Plus /></el-icon>
            新增物品
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table 
        :data="dataList" 
        v-loading="loading" 
        :fit="true"
        style="width: 100%"
      >
        <el-table-column prop="id" label="物品ID" min-width="200" show-overflow-tooltip />
        <el-table-column label="中文名称" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.name.zh || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="英文名称" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.name.en || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="阿语名称" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.name.ar || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="物品图片" min-width="120" show-overflow-tooltip>
          <template #default="{ row }">
            <el-avatar 
              :src="row.previewImageUrl" 
              :size="60" 
              class="good-avatar"
              @click="handlePreviewImage(row.previewImageUrl, row.name.zh || row.name.en || row.name.ar)"
              style="cursor: pointer;"
            />
          </template>
        </el-table-column>
                 <el-table-column label="物品动效" min-width="120" show-overflow-tooltip>
           <template #default="{ row }">
             <div class="animation-container">
               <div 
                 v-if="row.animationImageUrl && row.animationImageUrl.trim() !== ''" 
                 class="animation-preview"
                 @click="handlePreviewAnimation(row.animationImageUrl, row.name.zh || row.name.en || row.name.ar)"
                 style="cursor: pointer;"
               >
                 <el-icon><VideoPlay /></el-icon>
                 <span>动效文件</span>
               </div>
               <div v-else class="no-animation">
                 <el-icon><VideoPlay /></el-icon>
                 <span>无动效</span>
               </div>
             </div>
           </template>
         </el-table-column>
         <el-table-column label="动效文件类型" min-width="120" show-overflow-tooltip>
           <template #default="{ row }">
             <div v-if="row.animationImageUrl && row.animationImageUrl.trim() !== ''">
               <el-tag :type="getAnimationFileTypeTag(row.animationImageUrl)">
                 {{ getAnimationFileType(row.animationImageUrl) }}
               </el-tag>
             </div>
             <span v-else>-</span>
           </template>
         </el-table-column>
                 <el-table-column prop="category" label="物品类型" min-width="120" show-overflow-tooltip>
           <template #default="{ row }">
             <el-tag :type="getCategoryTagType(row.category)">
               {{ getCategoryName(row.category) }}
             </el-tag>
           </template>
         </el-table-column>
        <el-table-column label="上架状态" min-width="100" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag :type="row.enable ? 'success' : 'danger'">
              {{ row.enable ? '已上架' : '未上架' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ formatDate(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button 
              :type="row.enable ? 'warning' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)"
            >
              {{ row.enable ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageInfo.page"
          v-model:page-size="pageInfo.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 图片预览弹框 -->
    <ImagePreview
      v-model="previewVisible"
      :image-url="previewImageUrl"
      :title="previewTitle"
    />

    <!-- 动效预览弹框 -->
    <el-dialog
      v-model="animationPreviewVisible"
      :title="animationPreviewTitle"
      width="600px"
      class="animation-preview-dialog"
    >
      <div class="animation-preview-content">
        <div class="animation-info">
          <p><strong>动效文件：</strong>{{ animationPreviewUrl }}</p>
          <p><strong>文件格式：</strong>{{ getFileExtension(animationPreviewUrl) }}</p>
          <p><strong>说明：</strong>点击下方按钮可以下载文件或复制链接</p>
        </div>
        <div class="animation-actions">
          <el-button type="primary" @click="downloadAnimation">
            <el-icon><Download /></el-icon>
            下载动效文件
          </el-button>
          <el-button @click="copyAnimationUrl">
            <el-icon><CopyDocument /></el-icon>
            复制链接
          </el-button>
          <el-button type="success" @click="openAnimationInNewTab">
            <el-icon><Link /></el-icon>
            新窗口打开
          </el-button>
        </div>
      </div>
         </el-dialog>

     <!-- 物品表单弹框 -->
     <GoodForm
       v-model="goodFormVisible"
       :good-data="currentGoodData"
       :is-edit="isEditMode"
       @submit="handleFormSubmit"
     />
   </div>
 </template>

<style scoped lang="less">
.good-list {
  padding: 20px;
  
  .mb {
    margin-bottom: 20px;
  }
  
  .good-avatar {
    border: 1px solid #e4e7ed;
    transition: transform 0.3s;
    
    &:hover {
      transform: scale(1.1);
    }
  }
  
  .animation-container {
    display: flex;
    align-items: center;
    
    .animation-preview {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #409eff;
      font-size: 12px;
      
      &:hover {
        color: #66b1ff;
      }
    }
    
    .no-animation {
      display: flex;
      align-items: center;
      gap: 5px;
      color: #909399;
      font-size: 12px;
    }
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;
  }
}

.animation-preview-dialog {
  .animation-preview-content {
    .animation-info {
      margin-bottom: 20px;
      
      p {
        margin: 10px 0;
        line-height: 1.6;
      }
    }
    
    .animation-actions {
      display: flex;
      gap: 10px;
      justify-content: center;
    }
  }
}
</style>